
// import {useCookies} from 'react-cookie';
import strutil from './stringutil';
import constants from '../constants';
import eventEmitter from './EventEmitter';
import { UserHelper } from '../helper';

class NetworUtil {
    
     prefix = "/api"
    //GET,POST,PUT,DELETE,TRACE,HEAD
     request = (path:string,method:string,headers?:any,queries?:any,paramsOrBody?:any,)=> {
        var uri = this.prefix+path;
       
        var fixedHeaders = NetworUtil.getheaders(headers);

        var body = NetworUtil.getbody(method,fixedHeaders,paramsOrBody);

        var nuri = NetworUtil.buildQueriedUrl(uri,queries) || "";

        return new Promise((resolve,reject)=>{
            fetch(nuri,{
                method,
                headers:fixedHeaders,
                body:body
            }).then((resp)=>{
                console.debug("response status text:" + resp.statusText);
                return resp.json().then((text)=>{
                    return {
                        status:resp.status,
                        message:text,
                    }    
                })
            }).then((json)=>{
                console.info(JSON.stringify(json.message));
                if(json.status !== 200){
                    if(json.status === 401){
                        eventEmitter.dispatch(constants.str.network.err401);
                    }
                    reject(json.message);
                }
                else{
                    resolve(json.message); 
                }
            }).catch((err)=>{
                // unhandle request error
                console.debug(err)
                reject(err)
            })
        })
    }

    get = (path:string,request?:{headers?:any,queries?:any})=>{
        return this.request(path,"GET",request?.headers,request?.queries)
    }

    post = (path:string,request?:{headers?:any,queries?:any,params?:any})=>{
        return this.request(path,"POST",request?.headers,request?.queries,request?.params)
    }

    put = (path:string,request?:{headers?:any,queries?:any,params?:any})=>{
        return this.request(path,"PUT",request?.headers,request?.queries,request?.params)
    }
    
    delete = (path:string,request?:{headers?:any,queries?:any,params?:any})=>{
        return this.request(path,"DELETE",request?.headers,request?.queries,request?.params)
    }

    static getheaders = (headers:any)=> {
        
        var userInfo = UserHelper.getCachedUserInfo();
        
        console.info("got user info from cache: "+JSON.stringify(userInfo));
        const defaultHeaders = {
            "Content-Type":"application/json",
            "Accept":"application/json",
            'authorization':userInfo.token || ""
        };
        var fixedHeaders = Object.assign(defaultHeaders,headers);
        return fixedHeaders;
    }

    static getbody = (method:any,headers:any,paramsOrBody:any)=> {
        var body:any = "";
        if(method === "GET" || method === "HEAD"){
            body = null;
        }else{
            if(headers['Content-Type']?.includes("json")){
                body = JSON.stringify(paramsOrBody);
            }else{
                body = paramsOrBody;
            }
        }
        return body;
    }

    static buildQueriedUrl = (uri?:string,queries?:any) => {
        var queryStr = "";
        if(queries){
            let keys = Object.keys(queries);
            for(let i=0;i< keys.length; i++){
                let key = keys[i];
                queryStr += (i===0? "":"&")+(key+"="+queries[key]);
            }    
        }
        var nuri = uri;
        if(!strutil.isNullOrEmpty(queryStr)){
            nuri = uri+"?"+queryStr;
        }
        return nuri;
    }
}

const networkutil = new NetworUtil();

export default networkutil;